#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
import copy
from tkinter import messagebox
from tkinter import ttk
from ttkbootstrap import Style


class LJGui():
    def __init__(self, view_json: str):
        self.view_json = view_json
        self.doms = {}

        self.win = tk.Tk()
        style = Style(theme="flatly")
        self.win.configure(style=style)

        self.__parse()

        # 使用协议机制与窗口交互，并回调用户自定义的函数
        # self.win.protocol('WM_DELETE_WINDOW', self.alert_msg('测试消息'))

    def show(self):
        self.win.mainloop()

    def alert_msg(self, msg):
        return messagebox.showinfo(msg)

    def listen_click(self, dom_id, func):
        self.doms.get(dom_id).bind("<Button-1>", func)

    def __parse(self):
        """
        解析器：用于解析传入的view_json数据
        """
        view_json = copy.deepcopy(self.view_json)
        # 解析跟面板
        self.__gen_win(view_json)

        for item in view_json.get('children') or []:
            self.__gen_dom(item)

    def __gen_win(self, dict):
        self.win.title(dict.get('title'))

    def __gen_dom(self, dict):
        # 去除并删除id
        id = dict.get('id')
        if id:
            del dict['id']
        # 去除并删除类型
        type = dict.get('type')
        del dict['type']
        # 生成元素 - 这里后面需要细化
        dom = getattr(tk, type)(master=self.win, **dict)
        # dom = getattr(tk, type)(master=self.win, bg='#eee', bd='1', font=('宋体', 20), **dict)
        dom.pack()
        # 存储元素
        if id:
            self.doms[id] = dom

        # 子元素处理
